#pragma once

#include<iostream>
#include<pthread.h>
#include<string>
#include<cstring>
#include<cassert>
#include<functional>
#include<unistd.h>

class Thread;

//上下文
class Context
{
public:
    Thread* _this;
    void* _args;
public:
    Context():_this(nullptr),_args(nullptr)
    {}
    ~Context()
    {}
};

class Thread
{
public:
    //using func_t = std::function<void*(void*)>;
    typedef std::function<void*(void*)> func_t;
    const int num=1024;
public:
    Thread(func_t func,void* args,int number):_func(func),_args(args)
    {
        //_name="thread-";
        //_name+=std::to_string(number);
        char buffer[num];
        snprintf(buffer,sizeof(buffer),"thread-%d",number);
        _name=buffer;

        Context* ctx=new Context();
        ctx->_this=this;
        ctx->_args=_args;
        int n=pthread_create(&_tid,nullptr,start_routine,ctx);
        assert(n==0);
        (void)n;
    }
    //在类内创建线程，想让线程执行对应的方法，需要将方法设置为static
    static void* start_routine(void* args)//类内成员，有缺省参数
    {
        Context* ctx=static_cast<Context*>(args);
        void* ret = ctx->_this->run(ctx->_args);
        delete ctx;
        return ret;
        //静态方法不能调用成员方法或者成员变量
        //return _func(_args);
    }

    void join()
    {
        int n=pthread_join(_tid,nullptr);
        assert(n==0);
        (void)n;
    }

    void* run(void* args)
    {
        return _func(args); 
    }

    ~Thread()
    {
        //do nothing
    }

private:
    std::string _name;
    func_t _func;
    void* _args;
    pthread_t _tid;
};